#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "dll.h"
#include "client.h"
#include "our/tier_app.h"

FILE *fclient = NULL;
packet_t pkt;

extern int numseq;

int main( int argc, char* argv[] )
{
    if( argc < 3 )
    {
        fprintf(stderr, "usage: ./client -[sr] filename\n");
		exit(1);
	}
	
    if( strlen(argv[1]) != 2 || argv[1][0] != '-' || ( argv[1][1] != 'r' && argv[1][1] != 's' ) )
    {
        fprintf(stderr, "usage: ./client -[sr] filename\n");
		exit(1);
	}

    fprintf(stderr, "\n*****************************************************\n\n");
    fprintf(stdout, "                   Cliente iniciado!\n\n");
    fprintf(stderr, "*****************************************************\n\n");

    app_client_init( argv[2], argv[1][1] );

    fprintf(stderr, "\n******************************************************\n\n");
    fprintf(stdout, "             Cliente terminado com sucesso!\n\n");
    fprintf(stderr, "******************************************************\n\n");
	
    return 0;
}

/*
 * Primeira menssagem enviada do cliente para o servidor
 * filename contem o nome do arquivo
 * t indica se eh para receber um arquivo (r) ou enviar (s). 
*/
void app_client_init( char* filename, char t )
{
	int flen = strlen(filename); 
	int msglen;

	assert( t == 'r' || t == 's' );

	if( flen > MAX_FNAME )
    {
		fprintf(stderr, "O nome do arquivo nao pode ser maior que %d!\n", MAX_FNAME);
		exit(1);
	}

	pkt = app_init();
	app_set_h(&pkt, t);
	memcpy(pkt + APP_H, filename, flen+1);
	msglen = flen + APP_H + 1;
    
    /* Recebe Arquivo */
	if( t == 'r' )
    { 
		fclient = fopen(filename, "w");
	}
    /* Envia Arquivo */
	else if( t == 's' )
    {
		fclient = fopen(filename, "r");
	}

	if( !fclient )
    {
		char error[MAX_FNAME + 50];
		sprintf(error, "O cliente nao conseguiu abrir o arquivo %s (%c)\n", filename, t);
		app_fileerror(error, &pkt);
        app_end(&pkt);
		exit(1);
	}

	app_send( &pkt, msglen );

	if( t == 'r' )
    {
		app_cs_recv( &pkt, &fclient );
	}
	else if( t == 's' )
    {
		app_cs_send( &pkt, &fclient );
	}

	fclose(fclient);
	app_end(&pkt);
    
    return;
}
